import 'dart:io';
import 'package:video_player/video_player.dart';
import 'package:path_provider/path_provider.dart';

class VideoResourceHelper {
  static Future<VideoPlayerController?> createVideoController(
    String videoPath,
  ) async {
    try {
      VideoPlayerController controller;

      if (_isAssetPath(videoPath)) {
        controller = VideoPlayerController.asset(videoPath);
      } else if (_isNetworkPath(videoPath)) {
        controller = VideoPlayerController.networkUrl(Uri.parse(videoPath));
      } else {
        if (videoPath.startsWith('/')) {
          final localFile = File(videoPath);
          if (await localFile.exists()) {
            controller = VideoPlayerController.file(localFile);
          } else {
            throw Exception('Local video file not found: $videoPath');
          }
        } else {
          final localFile = await _getLocalVideoFile(videoPath);
          if (localFile != null && await localFile.exists()) {
            controller = VideoPlayerController.file(localFile);
          } else {
            controller = VideoPlayerController.asset(videoPath);
          }
        }
      }

      return controller;
    } catch (e) {
      return null;
    }
  }

  static bool _isAssetPath(String path) {
    return path.startsWith('assets/') || path.startsWith('/assets/');
  }

  static bool _isNetworkPath(String path) {
    return path.startsWith('http://') || path.startsWith('https://');
  }

  static Future<File?> _getLocalVideoFile(String fileName) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDirectory = Directory('${directory.path}/videos');

      if (!await videoDirectory.exists()) {
        await videoDirectory.create(recursive: true);
      }

      final file = File('${videoDirectory.path}/$fileName');
      return file;
    } catch (e) {
      return null;
    }
  }

  static Future<bool> checkVideoExists(String videoPath) async {
    try {
      if (_isAssetPath(videoPath)) {
        return true;
      } else if (_isNetworkPath(videoPath)) {
        return true;
      } else {
        if (videoPath.startsWith('/')) {
          final localFile = File(videoPath);
          return await localFile.exists();
        } else {
          final localFile = await _getLocalVideoFile(videoPath);
          return localFile != null && await localFile.exists();
        }
      }
    } catch (e) {
      return false;
    }
  }

  /// 获取视频文件大小
  static Future<int?> getVideoFileSize(String videoPath) async {
    try {
      if (_isAssetPath(videoPath) || _isNetworkPath(videoPath)) {
        // Assets 和网络文件无法直接获取大小
        return null;
      } else {
        final localFile = await _getLocalVideoFile(videoPath);
        if (localFile != null && await localFile.exists()) {
          return await localFile.length();
        }
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  static Future<bool> deleteLocalVideo(String fileName) async {
    try {
      final localFile = await _getLocalVideoFile(fileName);
      if (localFile != null && await localFile.exists()) {
        await localFile.delete();
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  static Future<String?> copyVideoToLocal(
    String sourcePath,
    String fileName,
  ) async {
    try {
      final sourceFile = File(sourcePath);
      if (!await sourceFile.exists()) {
        return null;
      }

      final localFile = await _getLocalVideoFile(fileName);
      if (localFile != null) {
        await sourceFile.copy(localFile.path);
        return localFile.path;
      }
      return null;
    } catch (e) {
      return null;
    }
  }

  static Future<String?> generateVideoThumbnail(String videoPath) async {
    try {
      return null;
    } catch (e) {
      return null;
    }
  }

  static Future<String?> getLocalVideoDirectoryPath() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDirectory = Directory('${directory.path}/videos');

      if (!await videoDirectory.exists()) {
        await videoDirectory.create(recursive: true);
      }

      return videoDirectory.path;
    } catch (e) {
      return null;
    }
  }

  static Future<List<String>> listLocalVideos() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDirectory = Directory('${directory.path}/videos');

      if (!await videoDirectory.exists()) {
        return [];
      }

      final files = await videoDirectory.list().toList();
      return files
          .whereType<File>()
          .map((file) => file.path.split('/').last)
          .toList();
    } catch (e) {
      return [];
    }
  }

  static Future<bool> clearAllLocalVideos() async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final videoDirectory = Directory('${directory.path}/videos');

      if (await videoDirectory.exists()) {
        await videoDirectory.delete(recursive: true);
        return true;
      }
      return false;
    } catch (e) {
      return false;
    }
  }

  static List<String> getSupportedVideoFormats() {
    return ['.mp4', '.mov', '.avi', '.mkv', '.webm', '.flv', '.wmv'];
  }

  static bool isSupportedVideoFormat(String fileName) {
    final extension = fileName.toLowerCase().substring(
      fileName.lastIndexOf('.'),
    );
    return getSupportedVideoFormats().contains(extension);
  }
}
